package com.soft.collateral.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.soft.collateral.entity.RoleMenu;
import com.soft.collateral.entity.Roles;
import com.soft.collateral.entity.UserRole;
import com.soft.collateral.exception.CollateralException;
import com.soft.collateral.mapper.RoleMenuMapper;
import com.soft.collateral.mapper.RolesMapper;
import com.soft.collateral.mapper.UserRoleMapper;
import com.soft.collateral.service.RolesService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 用户职能表 服务实现类
 * </p>
 *
 * @author liubin
 * @since 2025-07-25
 */
@Service
@RequiredArgsConstructor
public class RolesServiceImpl extends ServiceImpl<RolesMapper, Roles> implements RolesService {

    private final UserRoleMapper userRoleMapper;

    /**
     * 根据用户id查询角色
     * @param userId
     * @return
     */
    @Transactional(readOnly=true)
    @Override
    public List<Integer> getRolesByUserId(int userId) {
        LambdaQueryWrapper<UserRole> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserRole::getUserId, userId);
        List<Integer> roleIds = userRoleMapper.selectList(wrapper).stream().map(UserRole::getRoleId).collect(Collectors.toList());
        return roleIds;
    }

    /**
     * 重写删除方法，先检查此角色是否被占用
     * @param id
     * @return
     */
    @Override
    @Transactional
    public boolean deleteById(Integer id) {

        //1.先检查此角色是否被占用
        LambdaQueryWrapper<UserRole> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserRole::getRoleId , id);
        Long count = userRoleMapper.selectCount(wrapper);
        if(count>0){
            throw new CollateralException("此角色被占用！");
        }
        //2.未占用的检查项，则允许被删除
        int i = baseMapper.deleteById(id);
        return i>0?true:false;
    }

}
